package com.ruoyi.medicine.service.impl;

import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import com.ruoyi.common.core.redis.RedisCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import com.ruoyi.medicine.mapper.DocStocksMapper;
import com.ruoyi.medicine.domain.DocStocks;
import com.ruoyi.medicine.service.IDocStocksService;

/**
 * 商品库存Service业务层处理
 * 
 * @author ruoyi
 * @date 2025-08-14
 */
@Service
public class DocStocksServiceImpl implements IDocStocksService 
{
    @Autowired
    private DocStocksMapper docStocksMapper;

    @Autowired
    private RedisCache redisCache;
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 查询商品库存
     * 
     * @param drugId 商品库存主键
     * @return 商品库存
     */
    @Override
    public DocStocks selectDocStocksByDrugId(Long drugId)
    {
        return docStocksMapper.selectDocStocksByDrugId(drugId);
    }

    @Override
    public List<DocStocks> selectDocStocksList(DocStocks docStocks) {
        // 获取分页信息
        com.ruoyi.common.core.page.PageDomain pageDomain = com.ruoyi.common.core.page.TableSupport.buildPageRequest();

        // 生成总数缓存键，不包含分页信息
        String countCacheKey = generateCountCacheKey(docStocks);

        // 尝试从缓存获取总数
        Integer cachedCount = (Integer) redisTemplate.opsForValue().get(countCacheKey);

        // 查询总记录数（如果缓存不存在）
        if (cachedCount == null) {
            cachedCount = docStocksMapper.selectDocStocksListCount(docStocks);
            // 缓存总记录数
            redisTemplate.opsForValue().set(countCacheKey, cachedCount, 8, TimeUnit.HOURS);
        }
        // 直接查询数据库，让PageHelper处理分页（不缓存分页数据）
        return docStocksMapper.selectDocStocksList(docStocks);
    }

    /**
     * 生成总数缓存键（不包含分页信息）
     */
    private String generateCountCacheKey(DocStocks docStocks) {
        // 根据查询参数生成缓存键
        StringBuilder keyBuilder = new StringBuilder("medicine_stocks_count:");

        // 添加查询条件
        if (docStocks.getDrugType() != null) {
            keyBuilder.append("type:").append(docStocks.getDrugType()).append(":");
        }
        if (docStocks.getDrugName() != null) {
            keyBuilder.append("name:").append(docStocks.getDrugName()).append(":");
        }
        if (docStocks.getDrugState() != null) {
            keyBuilder.append("state:").append(docStocks.getDrugState()).append(":");
        }

        // 如果没有特定条件，则使用all
        if (keyBuilder.toString().equals("medicine_stocks_count:")) {
            keyBuilder.append("all");
        }

        return keyBuilder.toString();
    }

    /**
     * 新增商品库存
     * 
     * @param docStocks 商品库存
     * @return 结果
     */
    @Override
    public int insertDocStocks(DocStocks docStocks)
    {
        return docStocksMapper.insertDocStocks(docStocks);
    }

    /**
     * 修改商品库存
     *
     * @param docStocks 商品库存
     * @return 结果
     */
// ... existing code ...
    @Override
    public int updateDocStocks(DocStocks docStocks)
    {
        // 清除药品库存缓存
        try {
            // 使用通配符模式删除所有药品库存相关缓存
            Set<String> dataKeys = redisTemplate.keys("medicine_stocks_data:*");
            Set<String> countKeys = redisTemplate.keys("medicine_stocks_count:*");

            if (dataKeys != null && !dataKeys.isEmpty()) {
                redisTemplate.delete(dataKeys);
            }

            if (countKeys != null && !countKeys.isEmpty()) {
                redisTemplate.delete(countKeys);
            }

            redisTemplate.delete("medicine_stocks_by_type");

            System.out.println("成功清除药品库存相关缓存");
        } catch (Exception e) {
            System.err.println("Failed to clear medicine stocks cache: " + e.getMessage());
        }
        return docStocksMapper.updateDocStocks(docStocks);
    }

    @Override
    public int deleteDocStocksByDrugIds(Long[] drugIds)
    {
        // 清除所有相关缓存
        clearAllStocksCache();
        return docStocksMapper.deleteDocStocksByDrugIds(drugIds);
    }

    @Override
    public int deleteDocStocksByDrugId(Long drugId)
    {
        // 清除所有相关缓存
        clearAllStocksCache();
        return docStocksMapper.deleteDocStocksByDrugId(drugId);
    }

    /**
     * 清除所有药品库存相关缓存
     */
    private void clearAllStocksCache() {
        try {
            Set<String> dataKeys = redisTemplate.keys("medicine_stocks_data:*");
            Set<String> countKeys = redisTemplate.keys("medicine_stocks_count:*");

            if (dataKeys != null && !dataKeys.isEmpty()) {
                redisTemplate.delete(dataKeys);
            }

            if (countKeys != null && !countKeys.isEmpty()) {
                redisTemplate.delete(countKeys);
            }

            redisTemplate.delete("medicine_stocks_by_type");
            redisTemplate.delete("medicine_stocks_list:all");
        } catch (Exception e) {
            System.err.println("Failed to clear medicine stocks cache: " + e.getMessage());
        }
    }
}
